<?php
namespace App\Http\Controllers\Api\Product;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Product\Attribute as Model;

class Attribute extends Controller
{

    /**
     * 新增或编辑
     * @id id
     * @name name
     * @pid  父级id 默认0
     * @_id  自动生成
     * @type  暂时写死 0
     * @param Request $req
     * @return array
     */
    public function save(Request $req)
    {
        if (!$req->name || !$req->id) {
            return $this->resFail('数据有误！');
        }
        if ($req->_id) {
            $obj = Model::find($req->_id);
        } else {
            $obj = new Model;
        }

        $obj->fill($req->all());
        $obj->type = 0;

        // 检测
        if (!$obj->isIdValid()) {
            return self::resFail($obj->debug());
        }
        if ($obj->isIdExist()) {
            return self::resFail('该属性“'.$obj->id.'”已存在。');
        }
        $obj->save();

        return $this->resSuccess('保存成功。', $obj);

    }


    /** 属性详情
     * @param $_id string
     * @return array
     */
    public function detail (Request $req)
    {
        $res = Model::where('pid', 0)
            ->with('sub')
            ->find($req->get('_id'));
        return $this->resSuccess('属性详情获取成功。', $res);
    }


    /** 属性列表
     * @param Request $req
     * @return array
     */
    public function ls (Request $req)
    {
        $res = Model::where('pid', 0)->get();
        return $this->resSuccess('列表结果。', $res);
    }


    /** 属性列表
     * @param Request $req
     *
     * @return array
     */
    public function delete (Request $req)
    {
        $res = Model::where('_id', $req->_id)->delete();
        return $this->resSuccess('操作成功。', $res);
    }


}